package com.beyond.trace.service.impl.warn;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beyond.trace.domain.dto.warn.WarnRuleListDTO;
import com.beyond.trace.domain.pojo.warn.WarnRulePageQuery;
import com.beyond.trace.domain.warn.WarnRule;
import com.beyond.trace.mapper.WarnRuleMapper;
import com.beyond.trace.service.warn.WarnRuleService;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;

/**
 * @ClassName: WarnRuleServiceImpl
 * @author: z越
 * @date: 2023/2/24  10:00
 * @description 预警规则接口实现类
 */
@Service
public class WarnRuleServiceImpl extends ServiceImpl<WarnRuleMapper, WarnRule> implements WarnRuleService {

    @Autowired
    private RedisCache redisCache;
    @Override
    public Page<WarnRuleListDTO> findAllPages(WarnRulePageQuery query) {
        Page<WarnRule> page = new Page<>(query.getPageNum(),query.getPageSize());
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            query.setDepartId(String.valueOf(SecurityUtils.getUserDepartId()));
        }
        return this.baseMapper.findAllPages(page,query);
    }

    @Override
    public int openRule(Long id) {
        WarnRule warnRule = this.baseMapper.selectById(id);
        if (warnRule != null){
            warnRule.setStatus("OPEN");
            warnRule.setCreateTime(new Date());
            return this.baseMapper.updateById(warnRule);
        }
        return 0;
    }

    @Override
    public int offRule(Long id) {
        WarnRule warnRule = this.baseMapper.selectById(id);
        if (warnRule != null){
            warnRule.setStatus("OFF");
            warnRule.setCreateTime(new Date());
            return this.baseMapper.updateById(warnRule);
        }
        return 0;
    }

    @Override
    public int batchDelete(String ids) throws Exception{
        String[] id = ids.split(",");
        for (String s : id) {
            WarnRule warnRule = this.baseMapper.selectById(s);
            if(warnRule == null ) {
                throw new Exception("id为 "+ s +" 的规则未找到");
            }
            if(!"OFF".equals(warnRule.getStatus())) {
                throw new Exception(warnRule.getDeviceName()+" 的 "+warnRule.getRemark()+" 的规则未关闭");
            }
            redisCache.deleteObject(warnRule.getDeviceNo()+":"+warnRule.getId());
        }
        this.baseMapper.deleteBatchIds(Arrays.asList(id));
        return 1;
    }
}
